<template>
  <t-dialog
    :visible="visible"
    title="文档预览"
    width="70%"
    style="position: absolute"
    :close-btn="false"
    close-on-esc-keydown
    :footer="false"
    show-overlay
    placement="center"
    @close="onClose"
  >
    <template #default>
      <!-- 动态选择预览组件 -->
      <component :is="fileTypeComponent" v-if="fileTypeComponent" :src="file" />
      <!-- 如果文件类型不被支持 -->
      <div v-else>该文件类型不支持预览。</div>
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import { defineProps, defineEmits } from 'vue';
import type { PropType } from 'vue';
// office文件预览
import VueOfficePdf from '@vue-office/pdf';
import VueOfficeExcel from '@vue-office/excel';
import '@vue-office/excel/lib/index.css';
import VueOfficeDocx from '@vue-office/docx';
import '@vue-office/docx/lib/index.css';

interface Props {
  visible: boolean;
  file: string;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:visible']);

const fileTypeComponents = {
  docx: VueOfficeDocx,
  xlsx: VueOfficeExcel,
  pdf: VueOfficePdf,
} as const;

const fileType = computed(() => {
  return props.file ? props.file.slice(props.file.lastIndexOf('.') + 1).toLowerCase() : null;
});

const fileTypeComponent = computed(() => fileTypeComponents[fileType.value]);

const onClose = () => {
  emit('update:visible', false);
};
</script>
